// pages/list/list.js
import categoryTree from "../../assets/json/catgoryTree.js"
import {findAllcategory} from "../../api/category"
import {queryComment} from '../../api/comment'
import dayjs from 'dayjs'
import {
  listBehavior
} from "./behavior"
import { get } from "mobx-miniprogram"


Page({

  behaviors: [listBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    navList: ["点餐","评价"],
    // 右侧每个元素的高度数组
    heightArray: [],
    navIndex: 0,
    selectIndex: 0,
    categoryTree: [],
    scrollTop: 0,
    addressObj: null,
    // 评论列表
    commentList: []
  },

  showPopup() {
    this.changeShow(true)
  },

  checkNav(event) {
    this.setData({
      navIndex: event.currentTarget.dataset.index
    })
  },

  onClose() {
    this.changeShow(false)
  },

  navigatorDetail(event) {
    // 获取点击对应的奶茶商品对象
    const {
      detailobj
    } = event.currentTarget.dataset
    this.updateDetailObj(detailobj)
    wx.navigateTo({
      url: '/pages/detail/detail',
    })
  },

  // 获取每个list-array 的高度和
  getHeightCountArray() {
    let count = 0
    const heightCountArray = this.data.heightArray.map(item => {
      count += item
      return count
    })
    this.setData({
      heightCountArray
    })
  },

  selectList(event) {
    if (!this.data.heightCountArray) {
      this.getHeightCountArray()
    }
    const {
      index
    } = event.currentTarget.dataset
    this.setData({
      selectIndex: index,
      scrollTop: index > 0 ? this.data.heightCountArray[index - 1] : 0
    })
  },

  onScroll(event) {
    if (!this.data.heightCountArray) {
      this.getHeightCountArray()
    }
    const {
      scrollTop
    } = event.detail
    if (this.data.heightCountArray[this.data.selectIndex] < scrollTop) {
      this.setData({
        selectIndex: this.data.selectIndex + 1
      })
    } else if (this.data.selectIndex > 0 && this.data.heightCountArray[this.data.selectIndex - 1] > scrollTop) {
      this.setData({
        selectIndex: this.data.selectIndex - 1
      })
    }
  },

  // 修改购物车商品数量
  changeCountNum(event) {
    // console.log(event);
    let index = event.currentTarget.dataset.index
    let count = event.detail
    console.log(index, count);
    this.changeCount(index, count)
  },
  // 清空购物车
  clearCartList(event) {
    wx.modal({
      content: '确定清空购物车吗？',
      cancelText: '我再想想',
      success: ({confirm}) => {
        // 如果确认清空购物车
        confirm && this.clearCardList()
      }
    })
  },

  changeCheck(event) {
    this.changeIsSend(event.detail.value)
  },

  async getCommentList() {
    // 获取店铺评论
    const {data} = await queryComment({storeid: this.data.storeObj.id})
    data.forEach(item => {
      item.rate = item.rate && JSON.parse(item.rate)
      item.createTime = dayjs(item.createTime).format("YYYY-MM-DD")
    })
    this.setData({
      commentList: data
    })
  },

  async onShow() {
    await this.getCommentList()

    // 导入当前categoryTree对象
    const res = await findAllcategory()
    const query = wx.createSelectorQuery().in(this); // 使用.in(this)来指定页面实例
    const heightArray = []
    for (let i = 0; i < this.data.categoryTree.length; i++) {
      (function (index) {
        query.select(`.list-array${index}`)
          .boundingClientRect((rect) => {
            heightArray[index] = rect.height
          }).exec();
      }(i))
    }
    
    this.setData({
      categoryTree: res.data,
      heightArray
    })
  },

  onReady() {
    // console.log(1);
    const query = wx.createSelectorQuery().in(this); // 使用.in(this)来指定页面实例
    const heightArray = []
    for (let i = 0; i < this.data.categoryTree.length; i++) {
      (function (index) {
        query.select(`.list-array${index}`)
          .boundingClientRect((rect) => {
            heightArray[index] = rect.height
          }).exec();
      }(i))
    }

    this.setData({
      heightArray
    })
  },

  // async onLoad() {
  //   // 导入当前categoryTree对象
  //   const res = await findAllcategory()
  //   const query = wx.createSelectorQuery().in(this); // 使用.in(this)来指定页面实例
  //   const heightArray = []
  //   for (let i = 0; i < this.data.categoryTree.length; i++) {
  //     (function (index) {
  //       query.select(`.list-array${index}`)
  //         .boundingClientRect((rect) => {
  //           heightArray[index] = rect.height
  //         }).exec();
  //     }(i))
  //   }
    
  //   this.setData({
  //     categoryTree: res.data,
  //     heightArray
  //   })
  // },

  toCheckout() {
    if (this.data.allCount === 0) return 
    wx.navigateTo({
      url: "/pages/checkout/checkout"
    })
  },

  toSelectPath() {
    wx.navigateTo({
      url: `/pages/selectPath/selectPath?isSend=${this.data.isSend}`,
    })
  },
})